package com.rockcent.third;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.Customer;
import com.rockcent.mall.lib.domain.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  过滤器
 * Created by zhangjh on 2017/1/13.
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accessToken = request.getHeader("accessToken");

        if(StringUtils.isBlank(accessToken)){
            accessToken = RequestUtils.getStringParameter(request,"accessToken");
        }

        if (StringUtils.isBlank(accessToken)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>("10001", "accessToken 不能为空")));
            response.getWriter().close();
            return false;
        }
        String customerId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + accessToken).get();
        if (StringUtils.isBlank(customerId)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>("10002", "accessToken 无效")));
            response.getWriter().close();
            return false;
        }


        return super.preHandle(request, response, handler);
    }
}
